/**
* @author Jan Lehnardt <jan@php.net>
* @author Thomas Weinert
* @copyright Copyright © 2007, Jan Lehnardt, All rights reserved.
* @license Revised BSD, do whatever you like but retain all copyright notices.
*/

var TinyMCE_TabJumpPlugin = {
	getInfo : function() {
		return {
			longname : 'Tab Jump',
			author : 'Jan Lehnardt <jan@php.net>',
			authorurl : 'http://jan.prima.de/',
			infourl : 'http://jan.prima.de/tabjump/',
			version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
		};
	},

	handleEvent : function(e) {
		var inst, h;
		if (!tinyMCE.isOpera && e.type == 'keydown' && e.keyCode == 9) {
			inst = tinyMCE.selectedInstance;

			var to = tinyMCE.getParam("tabjump_to", null);

			if (to) {
				var _to = tinyMCE.instances[tinyMCE.getEditorId(to)];
				if(_to) {
					_to.getWin().focus();
				} else {
					if($(to)) {
						$(to).focus();
					}
				}
			} else {
				var formObj = inst.formElement.form;
				var elementIndex = 0;

				//get the next form element after the textarea
				for (var i = 0; i < (formObj.elements.length - 1); i++) {
					if (inst.formElement == formObj.elements[i]) {
						elementIndex = i + 1;
						break;
					}
				}
				//move to the next form element that is not a part of tinymce
				var nextElementIndex = this._tabjump_getNextFormElement(formObj.elements, elementIndex);      
				//if the element index is now 0 - we need to jump over hidden elements again
				if (elementIndex > 0 && nextElementIndex == 0) {
					elementIndex = this._tabjump_getNextFormElement(formObj.elements, 0);
				} else {
					elementIndex = nextElementIndex;
				}

				//did we got a textarea?
				if (formObj.elements[elementIndex].nodeName == 'TEXTAREA') {
					//is this textarea replaced by tinymce
					for (var i in tinyMCE.instances) {
						if (tinyMCE.instances[i].formElement == formObj.elements[elementIndex]) {
							tinyMCE.instances[i].getWin().focus();
							tinyMCE.cancelEvent(e);
							return false; 
						}
					}
				}

				//focus next element
				formObj.elements[elementIndex].focus();
			}
			tinyMCE.cancelEvent(e);
			return false; 
		} 

		return true;
	},

	_tabjump_getNextFormElement : function(elements, currentIndex) {
		var elementIndex = currentIndex;
		for (var i = elementIndex; i < elements.length; i++) {
			var className = tinyMCE.getAttrib(elements[i], 'class');
			if (!String(className).match(/^mce/)) {
				if (elements[i].nodeName == 'INPUT') {
					if (tinyMCE.getAttrib(elements[i], 'type').match(/^hidden$/i)) {
						//ignore hidden elements
					} else {
						elementIndex = i;
						break;            
					}
				} else {
					elementIndex = i;
					break;
				}
			} else if ((i + 1) == elements.length) {
				//end of form - select first element
				elementIndex = 0;
			}
		}
		return elementIndex;
	}
};

tinyMCE.addPlugin("tabjump", TinyMCE_TabJumpPlugin);
/* EOF */